import { Button, Card, Input, Space, Popconfirm, Table, Pagination } from 'antd'
import React, { useEffect, useState } from 'react'
import PageBreadcrumb from '../../components/PageBreadcrumb'
import { getGoods, deleteGoods } from "../../api/goods.js";
import Message from '../../components/Message';
import moment from 'moment';
import { useNavigate } from 'react-router-dom';

const { Search } = Input;
const showTotal = (total) => `共 ${total} 条`;

const GoodsList = () => {
  const navigate = useNavigate();
  const text = '此操作将永久删除该商品数据, 是否继续?';
  // 表头
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      key: 'goods_name'
    },
    {
      title: '商品价格（元）',
      dataIndex: 'goods_price',
      key: 'goods_price',
    },
    {
      title: '商品重量',
      dataIndex: 'goods_weight',
      key: 'goods_weight',
    },
    {
      title: '创建时间',
      dataIndex: 'add_time',
      key: 'add_time',
      render: (add_time) => (
        <span>
          {
            moment(add_time).format("YYYY-MM-DD")
          }
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='link' onClick={() => handleEdit(record.goods_id)}>编辑</Button>
          <Popconfirm
            placement="top"
            title={text}
            onConfirm={() => handleDelete(record.goods_id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type='link'>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [queryInfo, setQueryInfo] = useState({
    query: "",
    pagenum: 1, // 当前的页数
    pagesize: 8, // 当前每页显示多少条数据
  });

  useEffect(() => {
    getListData()
  }, [queryInfo])

  // 查询列表
  const getListData = async () => {
    setLoading(true)
    const data = await getGoods(queryInfo).finally(() => {
      setLoading(false)
    });

    setData(data.goods)
    setTotal(data.total)
  };

  // 搜索
  const onSearch = (value) => {
    setQueryInfo({
      query: value,
      pagenum: 1,
      pagesize: 5
    })
  }

  // 监听页码值的改变
  const handlePagination = (page, pageSize) => {
    setQueryInfo({
      query: queryInfo.query,
      pagenum: page,
      pagesize: pageSize
    })
  }

  // 跳转添加商品
  const handleAdd = () => {
    navigate("/goods/add")
  };

  // 跳转编辑商品
  const handleEdit = (id) => {
    navigate(`/goods/edit/${id}`);
  };

  // 删除
  const handleDelete = async (id) => {
    await deleteGoods(id);
    Message("success", "删除成功");
    getListData();
  }

  return (
    <>
      <PageBreadcrumb>
        <span>商品管理</span>
        <span>商品列表</span>
      </PageBreadcrumb>

      <Card>
        <Space>
          <Search placeholder="请输入内容" onSearch={onSearch} style={{ width: 300 }} />
          <Button type="primary" onClick={handleAdd}>添加商品</Button>
        </Space>

        <Table
          rowKey="goods_id"
          bordered
          columns={columns}
          dataSource={data}
          pagination={false}
          loading={loading}
        />

        <Pagination
          total={total}
          current={queryInfo.pagenum}
          pageSize={queryInfo.pagesize}
          showSizeChanger
          showTotal={showTotal}
          onChange={handlePagination}
        />
      </Card>
    </>
  )
}

export default GoodsList
